package com.example.gobang.game;


import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 处理AI对战
 */
@Component
public class AiMatch {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RoomManger roomManger;

    private Queue<User> usersQueue = new LinkedList<>();

    //玩家在线状态
    @Autowired
    private OnlineUserManager onlineUserManager;


    public AiMatch(){
        new Thread(() -> {
            while(true){
                handleMatch(usersQueue);
            }
        }).start();
    }

    public void add(User user){
        synchronized (usersQueue){
            usersQueue.add(user);
            usersQueue.notify();
            System.out.println("用户进入AI对战");
        }
    }
    private void handleMatch(Queue<User> matchQueue) {
        synchronized (matchQueue){
            try {
                while (matchQueue.size() < 1){
                    matchQueue.wait();
                }
                // 1.取出玩家
                User player1 = matchQueue.poll();
                System.out.println("取出玩家AI开始");
                // 3. 将这玩家 和 ai加入到游戏房间中.
                Room room = new Room();
                room.setAi(true);
                roomManger.add(room, player1.getUserId(),-1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
